<!-- 列的详情弹窗 -->
<template>
  <el-dialog :title="colItem ? colItem.colName : '' + '详情'" v-model="dialogVisible" width="70%" modal draggable
    :close-on-click-modal="false" :append-to-body="true" :before-close="handleClose">
    <seeColData ref="seeColData"></seeColData>

    <div style="display: flex; justify-content: space-between; align-items: center">
      <div class="flex justify-between align-center" style="width: 100%">
        <el-radio-group v-model="zyType" v-if="isShowRadio" @input="changePadio">
          <el-radio-button label="1">{{ zytypebutton == 0 ? 'A面' : '左面' }}</el-radio-button>
          <el-radio-button label="2">{{ zytypebutton == 0 ? 'B面' : '右面' }}</el-radio-button>
        </el-radio-group>
        <div>
          <span class="legend">&nbsp;<span style="background: #15a8ea"></span>&nbsp;在库&nbsp;</span>
          <span class="legend">&nbsp;<span style="background: #e06c76"></span>&nbsp;离库&nbsp;</span>
          <span class="legend">&nbsp;<span style="background: #f1f1f1"></span>&nbsp;剩余位置</span>
        </div>
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      </div>
    </div>
    <div class="container">
      <div v-for="(row, rowIndex) in colData" :key="rowIndex" class="row">
        <div v-for="(cell, cellIndex) in row" :key="cellIndex" class="cell"
          @click="handleCellPostionId(cell, cellIndex)">
          <em v-for="(item, index) in cell.boxLi" :key="item.labelId">
            <span class="boxlis" :style="{
              width: OneboxWidth(cell)[index] + '%',
              background: cell.boxLi[index].storeStatus == 1 ? '#15a8ea' : '#e06c76',
            }" v-if="OneboxWidth(cell)[index] != 0"></span>
          </em>
          <em>
            <span class="amslis" :style="{
              width: `${amsCcolWidth(cell)}%`,
              background: isArchivesOut(cell)
                ? 'linear-gradient(to right, #15a8ea 70%, #e06c76 10%)'
                : '#15a8ea',
            }" v-if="amsCcolWidth(cell) != 0">
            </span>
          </em>
          <em class="emptyBox" :style="{ width: remainingWidth(cell) + '%' }"></em>
          <div class="overlay-text no-select">
            {{ cell.positionName }}
          </div>
          <i v-show="isSelected(cell)"
            :class="['iconfont', 'icon-jiaobiaoxuanzhong', { 'active-jiaobiao': isSelected(cell) }]"></i>
        </div>
      </div>
    </div>
    <el-empty v-if="isShowEmpty" description="暂无获取到数据"></el-empty>

    <span slot="footer" class="dialog-footer" v-show="showClick">
      <span class="select-position">
        <span style="font-size: 16px; white-space: nowrap"> 已选择的库位:</span>
        <div>
          <el-tag :key="tag.positionId" v-for="tag in selectedPositions" closable :disable-transitions="false"
            @close="handleTagClose(tag)">
            {{ tag.positionName }}
          </el-tag>
        </div>
      </span>
      <span style="display: flex; justify-content: space-between">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="SubmitPostionId" size="small">选择库位</el-button>
      </span>
    </span>
  </el-dialog>
</template>

<script>
// import { EventBus } from '@/utils/EventBus'
import { cabinetDiv } from '@/api/rfid/virtualRepository.js'
import SeeColData from '@/components/seeColData.vue'
export default {
  name: 'InventoryColDetails',
  components: {
    SeeColData,
  },
  props: {
    colItem: {
      type: Object,
      default: () => {
        return {
          colName: null,
        }
      },
    },
    upItemWidth: {
      type: Number,
      default: 0,
    },
    showClick: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      dialogVisible: false,
      zyType: '1',
      colData: [],
      loading: false,
      tableData: [],
      showFlag: false,
      currentIndex: null,
      clickCurrentIndex: null,
      activeItem: {},
      isProcessing: false, //重复点击事件的标识
      isShowRadio: false,
      isShowEmpty: false,
      slectlist: [],
      cabinetDiv: [],
      selectedPositions: [], // 选择后的库位
      zytypebutton: 0,
      isIndeterminate: false,
      checkAll: false,
    }
  },
  computed: {
    // 判断库位上的档案有没有出库的
    isArchivesOut() {
      return function (val) {
        return val.archiveLi.some((item) => item.storeStatus == 2)
      }
    },
    // 重新计算档案占库位的宽度
    amsCcolWidth() {
      return function (val) {
        // 将val这个数组中的pageNo相加起来
        // 获取到当前库位上档案的所有宽度,
        const allAmsWidth = val.archiveLi.reduce(
          (accumulator, currentValue) => accumulator + currentValue.pageNo,
          0
        )
        // 如果这个值大于0，则进行下一步的逻辑
        if (allAmsWidth > 0) {
          // 获取到系统重定义的多少页为1厘米
          const cmPageNo = JSON.parse(localStorage.getItem('cmPageNo'))
          if (cmPageNo) {
            //  将allAmsWidth和cmPageNo比较，如果比这个小的话，就返回1，否则就allAmsWidth除以cmPageNo，保留两位小数
            if (allAmsWidth <= cmPageNo) {
              return 1
            } else {
              return parseFloat((allAmsWidth / cmPageNo / val.divWidth) * 100).toFixed(0)
            }
          } else {
            return 0
          }
        } else {
          return 0
        }
      }
    },
    // 计算每个格子的宽度
    OneboxWidth() {
      return function (val) {
        const totalWidth = val.divWidth
        return val.boxLi.map((box) => {
          const percentage = Math.round((box.boxWidth / totalWidth) * 100)
          return percentage
        })
      }
    },
    // 计算剩余的宽度
    remainingWidth() {
      return function (val) {
        const allWidth = this.OneboxWidth(val)
        const children = val.boxLi.length
        return (
          100 -
          (this.amsCcolWidth(val) > 0 ? Number(this.amsCcolWidth(val)) : 0) -
          allWidth.reduce((accumulator, currentValue) => accumulator + currentValue, 0)
        )
      }
    },
    isSelected() {
      return function (val) {
        const result = this.selectedPositions.some(
          (item) => JSON.stringify(item) === JSON.stringify(val)
        )
        return result
      }
    },
  },

  watch: {
    selectedPositions(value) {
      this.isIndeterminate = value.length > 0 && value.length < this.cabinetDiv.length
    },
  },
  methods: {
    changePadio() {
      this.getDivData(this.colItem)
    },
    handleTagClose(tag) {
      this.selectedPositions.splice(this.selectedPositions.indexOf(tag), 1)
    },
    hasPositionId(cell) {
      return this.colData.includes(cell)
    },
    // 全选库位的方法
    handleCheckAllChange() {
      this.colData.map((x) => {
        x.map((y) => {
          this.addObject(y)
        })
      })
    },
    addObject(obj) {
      // 检查数组中是否有相同的对象
      const exists = this.selectedPositions.some((item) => item.positionId === obj.positionId)
      if (!exists) {
        // 如果不存在，则添加对象
        this.selectedPositions.push(obj)
      } else {
        this.selectedPositions.splice(this.selectedPositions.indexOf(obj), 1)
      }
    },

    handleCellPostionId(cell) {
      this.addObject(cell)
      if (!this.isProcessing) {
        this.isProcessing = true
        // 点击获取库位的id
        this.clickCurrentIndex = cell.positionId
        this.activeItem = cell

        const isUP = (this.upItemWidth / cell.divWidth) * 100 > this.remainingWidth(cell)
        if (isUP) {
          this.$message.error('该格子剩余空间不足，无法上架')
        }

        setTimeout(() => {
          this.isProcessing = false
        }, 1000) // 1秒后重置isProcessing
      }
    },
    // 提交库位id
    SubmitPostionId(flag) {
      const isUP =
        (this.upItemWidth / this.activeItem.divWidth) * 100 > this.remainingWidth(this.activeItem)
      if (isUP) {
        this.$message.error('该格子剩余空间不足，无法上架')
      } else {
        // EventBus.$emit('submitPostion', this.selectedPositions, '2')
        this.dialogVisible = false
        this.$emit('handleClose')
      }
    },
    // 重新渲染查看表格
    reloadTable() {
      setTimeout(() => {
        const cell = this.cabinetDiv.filter((x) => x.positionName == this.innerDialogTitle)[0]
        this.handleCellClick(cell)
      }, 1000)
    },

    // 处理数组
    handleArray(boxLi, archiveLi) {
      // 创建一个Map来存储b数组中的boxNo
      let bMap = new Map()
      boxLi.forEach((item) => {
        item.children = []
        bMap.set(item.boxNo, item)
      })
      // 创建一个新数组，复制boxLi的元素
      let newBoxLi = boxLi.slice()
      // 遍历a数组，根据boxNo将a中的对象添加到b中的对应对象中
      archiveLi.forEach((item) => {
        let bItem = bMap.get(item.boxNo)
        if (bItem) {
          if (!bItem.children) {
            bItem.children = []
          }
          bItem.children.push(item)
        } else {
          newBoxLi.push(item)
        }
      })

      const result = newBoxLi.map((item) => {
        // 如果 children 不存在，则添加一个空数组
        if (!item.children) {
          item.children = []
        }
        return item
      })
      return result
    },
    // 获取每个格子的数据
    getDivData(val) {
      this.loading = true
      const params = {
        colId: val.colId, //列id
        zy: this.zyType, //左右面
      }
      // 根据节层生成对应的格子
      cabinetDiv(params).then((res) => {
        if (res.data.code == 200) {
          this.isShowEmpty = false
          this.cabinetDiv = res.data.data
          this.colData = this.createCustomArray(val.leNum, val.divNum, res.data.data)
          // 延迟500ms
          // setTimeout(() => {
          //   this.loading = false
          // }, 500)
        } else {
          this.colData = []
          setTimeout(() => {
            this.loading = false
          }, 500)
          this.isShowEmpty = true
          this.$message.warning(res.data.message)
        }
      })
    },
    // 生成自定义长宽的格子
    createCustomArray(rows, cols, positions) {
      // 使用 Array.from 创建一个长度为 cols 的数组，数组中的每个元素都是一个长度为 rows 的数组，初始值为 null
      let result = Array.from({ length: cols }, () => Array.from({ length: rows }, () => null))
      // 遍历 positions 数组，将每个元素的 divNo 和 leNo 转换为 row 和 col，并将该元素赋值给 result 数组中的对应位置
      positions.forEach((p) => {
        let row = p.divNo - 1
        let col = p.leNo - 1
        result[row][col] = p
      })
      // 返回 result 数组
      return result
    },

    handleClose() {
      this.dialogVisible = false
    },
    show(flag, colItem, zytype) {
      this.dialogVisible = true
      if (flag == undefined) {
        this.zyType == '1'
        this.isShowRadio = true
      } else {
        this.zyType = flag
      }
      this.zytypebutton = zytype
      this.getDivData(colItem)
    },
  },
  created() { },
  mounted() { },
}
</script>
<style lang="less" scoped>
.container {
  display: flex;
  flex-wrap: wrap;
  // width: 300px;
  margin: 10px auto;
  border: 1px solid #ccc;
  max-height: 60vh;
  overflow: hidden;
  overflow: auto;
}

.row {
  display: flex;
  width: 100%;
  border-bottom: 1px solid #ccc;
}

.cell {
  position: relative;
  width: 100%;
  // flex: none; /* 确保每个盒子不会自动调整大小 */
  // min-width: calc(100% / 6.2); /* 确保至少有6个盒子的宽度 */

  height: 80px;
  padding: 5px;
  font-size: 16px;
  cursor: pointer;
  border-right: 1px solid #ccc;
  border-top: 1px solid #ccc;
  // 强制一行展示
  white-space: nowrap;
  // 溢出隐藏
  overflow: hidden;
  // 文字超出部分用省略号表示
  text-overflow: ellipsis;

  span {
    // margin-right: 1%;
    border-right: 1px solid #fff;
    box-sizing: border-box;

    &:last-child {
      margin-right: 0;
    }
  }

  .overlay-text {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #606266;
    text-align: center;
    // 强制一行展示
    white-space: nowrap;
    // 溢出隐藏
    overflow: hidden;
    // 文字超出部分用省略号表示
    text-overflow: ellipsis;
    opacity: 0.5;
    z-index: 999;
    /* 确保此元素在绝对定位元素之上 */
    padding: 5px;
  }
}

.emptyBox {
  position: relative;
  z-index: 1;
  background: #f1f1f1;
  height: 100%;
  display: inline-block;
}

.check {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 99;
}

.check .el-checkbox__label {
  display: none;
}

.infoBtn {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 99;
}

.active-jiaobiao {
  position: absolute;
  bottom: 0;
  right: 0;
  z-index: 99;
  color: #5a9cf8;
  font-size: 1rem
    /* 60/192 */
  ;
}

.row:last-child .cell {
  border-bottom: 1px solid #ccc;
}

.active {
  box-shadow: 0 1px 2px -2px rgba(90, 156, 248, 0.5), 0 3px 6px 0 rgba(90, 156, 248, 0.4),
    0 5px 12px 4px rgba(90, 156, 248, 0.2);
}

.cell:hover {
  box-shadow: 0 1px 2px -2px rgba(90, 156, 248, 0.5), 0 3px 6px 0 rgba(90, 156, 248, 0.1),
    0 5px 12px 4px rgba(90, 156, 248, 0.09);
}

.boxlis {
  height: 100%;
  display: inline-block;
}

.amslis {
  height: 100%;
  display: inline-block;
}

.legend {
  text-align: center;

  span {
    width: 20px;
    height: 10px;
    display: inline-block;
  }
}

.el-table {
  .archive-row {
    background: #d9ecff;
  }
}

.scrollable-row {
  overflow-x: auto;
  /* 添加水平滚动条 */
  overflow-y: auto;
  /* 添加垂直滚动条 */
  white-space: nowrap;
  /* 保持内容在同一行，以便显示水平滚动条 */
}

.el-tag+.el-tag {
  margin-left: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .select-position {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-right: 10px;
  }
}
</style>
